// https://vuex.vuejs.org/en/actions.html

// Actions are similar to mutations,
// the differences being that:
// Instead of mutating the state, actions commit mutations.
// Actions can contain arbitrary asynchronous operations.

// Action handlers receive a context object
// which exposes the same set of methods/properties on the store instance,
// so you can call context.commit to commit a mutation,
// or access the state and getters via context.state and context.getters.

// DO NOT directly modify the state in actions.
// Please use commit() to update the state.

// import * as types from './mutation-types';
import * as api from '@/api';
import API from '@/util/api';
import { Toast } from 'buefy/dist/components/toast';
const host = "https://api.xiuzhen.io/"

export default {
  async FETCH_ME({ commit }) {
    try {
      const me = await API.getMyInfo();
      if (me.eos_address) {
        commit('setUserInfo', me);
      } else {
        commit('setUserInfo', null);
      }
    } catch (e) {
      commit('setUserInfo', null);
    }
  },
  async updatePlayerInfo({ commit }, eos_address) {
      try {
        const playerInfoTable = await API.getPlayerInfoAsync();
        var playerInfoDict = new Object();
        for (var i=0; i<playerInfoTable.length;i++) {
          playerInfoDict[playerInfoTable[i].account] = playerInfoTable[i];
        }
        commit('setPlayerInfoDict', playerInfoDict);
        if (playerInfoDict[eos_address]) {
          commit('setPlayerInfo', playerInfoDict[eos_address]);
        }
      } catch (err) {
        console.error('Failed to fetch player info', err);
      }
    },
    async loginScatterAsync({ commit, dispatch }, inviteCode) {
      commit('setIsScatterLoggingIn', true);
      try {
        const identity = await API.loginScatterAsync();
        if (!identity) {
          commit('setScatterAccount', null);
          return;
        }
        const account = identity.accounts.find(({ blockchain }) => blockchain === 'eos');
        commit('setScatterAccount', account);
        dispatch('updatePlayerInfo', account.name);
        const userInfo = await API.registerOrLogin(account.name, inviteCode);
        commit('setUserInfo', userInfo);
        Toast.open({
          message: 'You successfully logged in Scatter!',
          type: 'is-success',
          queue: false,
        });
      } catch (err) {
        console.error('Failed to login Scatter', err);
        Toast.open({
          message: `Failed to log in Scatter: ${err.message}.`,
          type: 'is-danger',
          queue: false,
          duration: 5000,
        });
      }
      commit('setIsScatterLoggingIn', false);
  },
  async logoutAsync({commit, dispatch}) {
    const result = await API.logoutAsync();
    commit('setUserInfo', null);
  },
};
